//
//  ListDemo.swift
//  SwiftUIDemo
//
//  Created by Tilt Wang on 2025/6/29.
//

import SwiftUI

struct ListDemo: View {
    
    @State var fruits: [String] = [
        "apple", "orange", "banana", "peach"
    ]
    
    @State var veggies: [String] = [
        "tomato", "potato", "carrot"
    ]
    
    var body: some View {
        NavigationView {
            List {
                Section(header:
                            HStack {
                    Text("Fruits")
                    Image(systemName: "flame.fill")
                }
                    .font(.headline)
                    .foregroundColor(.orange)
                ) {
                    ForEach(fruits, id: \.self) { fruit in
                        Text(fruit.capitalized)
                    }
                    //                .onDelete { indexSet in
                    ////                    fruits.remove(atOffsets: indexSet)
                    //                    delete(indexSet: indexSet)
                    //                }
                    .onDelete(perform: delete)
                    .onMove(perform: move)
//                    .onMove( { indexSets, newOffset in
//                        fruits.move(fromOffsets: indexSets, toOffset: newOffset)
//                    })
                    .listRowBackground(Color.pink)
                }
                
                Section(header: Text("Veggies")) {
                    ForEach(veggies, id: \.self) { veggie in
                        Text(veggie.capitalized)
                    }
                    .onDelete(perform: delete)
                    .onMove(perform: move)
                }
            }
            .accentColor(.purple)
            //        .listStyle(SidebarListStyle())
            .navigationTitle("Grocery List ")
            .navigationBarItems(
                leading: EditButton(),
                trailing: addButton
            )
            
        }
        .accentColor(.red)
    }
    
    var addButton: some View {
        Button("Add") {
            add()
        }
    }
    
    func delete(indexSet: IndexSet) {
        fruits.remove(atOffsets: indexSet)
    }
    
    func move(indexSets: IndexSet, newOffset: Int) {
        fruits.move(fromOffsets: indexSets, toOffset: newOffset)
    }
    
    func add() {
        fruits.append("Coconut")
    }
    
}

#Preview {
    ListDemo()
}
